<template>
  <main-card :title="tagGroupDetail.name" :crumbs="crumbs">
    <template #tool-btn>
      <template v-if="!isConstantTagGroup">
        <a-space :size="8">
          <a-button
            v-auth="'algo-service-delete'"
            type="default"
            class="icon-with-btn"
            @click.stop="openDeleteTaskModal(tagGroupDetail.id)"
          >
            <i class="iconfont icon-delete-bin-line"></i>
            <span class="text">删除</span>
          </a-button>
          <a-button v-auth="'algo-service-edit'" type="default" class="icon-with-btn" @click.stop="editGroup(tagGroupDetail)">
            <i class="iconfont icon-edit-line"></i>
            <span class="text">编辑</span>
          </a-button>
          <a-button type="primary" @click="createTag">
            <span class="text">创建标签</span>
          </a-button>
        </a-space>
      </template>
    </template>

    <template #subheading>
      <div class="mt-12">{{ tagGroupDetail.description }}</div>
    </template>

    <div class="mb-48 fbc">
      <a-input
        v-model:value="pageForm.name"
        v-trim
        class="h-36"
        allow-clear
        placeholder="请输入名称"
        style="width: 328px"
        @keyup.enter="getDataList({ offset: 1 })"
      >
        <template #prefix> <i class="iconfont icon-search-line"></i> </template>
      </a-input>
    </div>

    <a-table
      v-model:expanded-row-keys="expandedRowKeys"
      :columns="tableColumns"
      :data-source="dataList"
      :pagination="false"
      :style="{ width: '100%' }"
      :loading="loading"
      row-key="id"
      @change="tableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'color'">
          <div v-if="record.color" class="color-block" :style="{ background: record.color }"></div>
          <span v-else>/</span>
        </template>

        <template v-else-if="column.dataIndex === 'tools'">
          <template v-if="isConstantTagGroup"> </template>
          <a-dropdown v-else @click.stop>
            <div class="more-btn"><i class="iconfont icon-more-line btn-icon"></i></div>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="editTag(record as DmpTag)">
                  <a>编辑标签</a>
                </a-menu-item>
                <a-menu-item @click="createSameLevelTag(record.id)">
                  <a>创建同级标签</a>
                </a-menu-item>
                <a-menu-item v-if="record.level <= 4" @click="createNextLevelTag(record.id)">
                  <a>创建下级标签</a>
                </a-menu-item>
                <a-menu-item @click="openDeleteTagModal(record.id)">
                  <a>删除标签</a>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
        <template v-else> </template>
      </template>
    </a-table>
    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
  </main-card>

  <edit-tag-modal ref="editTagModalRef" :after-close-fn="getDataList" :tag-group-id="tagGroupId" />
  <edit-tag-group-model ref="editTagGroupModelRef" :after-close-fn="getTagGroupDetail" />
</template>

<script lang="ts" setup>
  import type { TableProps } from 'ant-design-vue'
  import { message, Modal } from 'ant-design-vue'
  import { computed, createVNode, ref, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import WarnIcon from '@/components/icon/IconWarning/index.vue'
  import MainCard from '@/components/MainCard/index.vue'
  import useList from '@/hooks/use-list'
  import { dmpTaskApi } from '@/services'
  import { filterTableColumns } from '@/utils'

  import EditTagGroupModel from '../tag-group-list/components/EditModel.vue'
  import { DmpTag } from '../types'
  import EditTagModal from './components/EditModal.vue'

  const router = useRouter()
  const route = useRoute()

  const tagGroupId = route.params.id as string
  const crumbs = ref([{ name: '数据标注', path: '/dmp/task-list' }, { name: '标签组管理', path: '/dmp/tag-group-list' }, { name: '' }])

  /* 标签组------------------------------------------------------------------------------------------------- */
  const tagGroupDetail = ref({
    id: '',
    name: '',
    description: ''
  })

  // 是否是内置标签
  const isConstantTagGroup = computed(() => ['1'].includes(tagGroupDetail.value.id))

  const getTagGroupDetail = async () => {
    const { data } = await dmpTaskApi.tagGroupDetail({}, { urlParams: { id: tagGroupId } })
    tagGroupDetail.value = data

    crumbs.value.at(-1)!.name = tagGroupDetail.value.name
  }

  /* 新增or编辑 */
  const editTagGroupModelRef = ref<InstanceType<typeof EditTagGroupModel>>()
  const editGroup = (record: any) => {
    editTagGroupModelRef.value?.open(record)
  }
  /* 删除 */
  const openDeleteTaskModal = (id: string) => {
    Modal.confirm({
      title: `确定删除?`,
      icon: createVNode(WarnIcon),
      content: '当前标签组及所有组内标签将被删除，且不可恢复，请确认操作',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        await dmpTaskApi.tagGroupDel({}, { urlParams: { id }, isAddUid: true })
        message.success('删除成功')
        router.back()
      }
    })
  }

  /* 标签列表-------------------------------------------------------------------------------------------- */
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        width: 600
      },
      {
        title: '标签颜色',
        dataIndex: 'color',
        width: 120
      },
      {
        title: '属性',
        dataIndex: 'property'
      },
      {
        title: '操作',
        dataIndex: 'tools',
        width: 63
      }
    ])
  )

  const { getDataList, loading, pageForm, dataList } = useList(dmpTaskApi.tagList, {
    labelGroupId: tagGroupId,
    name: '',
    columns: 'createTime',
    order: ''
  })
  // 表哥展开行
  const expandedRowKeys = ref<string[]>([])
  // 根据列表动态暂开所有行
  watch(dataList, () => {
    expandedRowKeys.value = []
    setExpandKeys(dataList.value)
    console.log('expandedRowKeys', expandedRowKeys.value)
  })

  const tableChange: TableProps['onChange'] = (pagination, filters: any, sorter: any) => {
    pageForm.value.columns = sorter.field === 'updateTime' ? 'updateTime' : 'createTime'
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    getDataList({ offset: 1 })
  }

  /** 写入所有展开行的key */
  const setExpandKeys = (dataList: any[]) => {
    dataList.forEach(it => {
      if (it.children?.length) {
        expandedRowKeys.value.push(it.id)
        setExpandKeys(it.children)
      }
    })
  }

  const getTagDetail = async (id: string) => {
    const { data } = await dmpTaskApi.tagDetail({}, { urlParams: { id } })
    return data
  }
  /* 删除 */
  const openDeleteTagModal = (id: string) => {
    Modal.confirm({
      title: `确定删除?`,
      icon: createVNode(WarnIcon),
      content: '当前标签及所有下级标签将被删除，且不可恢复，请确认操作',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        await dmpTaskApi.tagDel({}, { urlParams: { id } })
        message.success('删除成功')
        getDataList()
      }
    })
  }

  /* 标签增加or编辑-------------------------------------------------------------------------------------------- */
  const editTagModalRef = ref<InstanceType<typeof EditTagModal>>()

  /**
   * 新增标签
   * @param pid 父标签id，无则为0
   * @param level 标签级别
   */
  const createTag = async () => {
    editTagModalRef.value?.open({
      pid: '0',
      level: 1
    })
    editTagModalRef.value?.editTitle('创建标签')
  }
  /**
   * 创建同级标签
   * @param copyAttrId 需要复制属性的标签id
   */
  const createSameLevelTag = async (copyAttrId: string) => {
    const detail = await getTagDetail(copyAttrId)
    editTagModalRef.value?.editTitle('创建同级标签')
    editTagModalRef.value?.open({
      pid: detail.pid,
      level: detail.level,
      propertyVoList: detail.propertyVoList
    })
  }
  /**
   * 创建下级标签
   * @param copyAttrId 需要复制属性的标签id
   */
  const createNextLevelTag = async (copyAttrId: string) => {
    const detail = await getTagDetail(copyAttrId)
    editTagModalRef.value?.editTitle('创建下级标签')
    editTagModalRef.value?.open({
      pid: detail.id,
      level: detail.level + 1,
      propertyVoList: detail.propertyVoList
    })
  }
  // 编辑标签
  const editTag = async (record: DmpTag) => {
    const detail = await getTagDetail(record.id)
    editTagModalRef.value?.editTitle('编辑标签')
    editTagModalRef.value?.open(detail)
  }
  /* ---------------------------------------------------------------------------------------------------------- */
  getTagGroupDetail()
  getDataList()
</script>

<style lang="less" scoped>
  .color-block {
    width: 24px;
    height: 24px;
    background: #4686ed;
    border-radius: 6px;
  }
</style>
